package onebound

import (
	"app/pkg/db"
	httpUtil "app/pkg/http"
	"app/pkg/log"
	"encoding/json"
	"fmt"

	"github.com/garyburd/redigo/redis"
)

// 万邦接口
type OneboundService struct{}

func New() *OneboundService { return &OneboundService{} }

// 抓取宝贝标题,宝贝主图,店铺名称结束(万邦接口)
func (s *OneboundService) tbItemGet(pid string) (reply ItemGetReply, err error) {
	url := fmt.Sprintf("https://api-gw.onebound.cn/taobao/item_get/?key=t8326628250&secret=20210814&num_iid=%s", pid)
	res, err := httpUtil.Get(url, map[string]string{}, 10)
	if err == nil {
		err = json.Unmarshal(res, &reply)
	} else {
		log.NewError("tbItemGet", map[string]interface{}{
			"url": url,
			"err": err,
		})
	}
	return
}

func (s *OneboundService) ShopGoodsInfo(pid string) (reply ItemReply, err error) {
	//加入缓存
	key := "shop_goods_info_cache:" + pid
	bytes, _ := redis.Bytes(db.DB.RedisPool.Get().Do("GET", key))
	if len(bytes) > 0 {
		err = json.Unmarshal(bytes, &reply)
		return
	}
	tbItem, err := s.tbItemGet(pid)
	if err != nil {
		return
	}
	reply = tbItem.Item
	if reply.Title != "" {
		cacheBytes, _ := json.Marshal(reply)
		redis.Bytes(db.DB.RedisPool.Get().Do("SET", key, string(cacheBytes), "EX", 180))
	}
	return
}

func (s *OneboundService) ItemSearchSuggest(q string) {
	url := fmt.Sprintf("https://api-gw.onebound.cn/taobao/item_search_suggest/?key=t8326628250&secret=20210814&q=%s", q)
	res, _ := httpUtil.Get(url, map[string]string{}, 10)
	fmt.Printf("%+v", string(res))
}
